package com.lixinlei.security.api.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.google.common.util.concurrent.RateLimiter;

/**
 * OncePerRequestFilter - 保证 Filter 中的逻辑在一个请求中，永远只会被执行 1 次，有些情况下，一个请求会多次过一个 Filter；
 */
@Component
@Order(1)
public class RateLimitFilter extends OncePerRequestFilter {

    // 每秒只放一个请求过去
    private RateLimiter rateLimiter = RateLimiter.create(1);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        System.out.println(1);

        if(rateLimiter.tryAcquire()) {
            filterChain.doFilter(request, response);
        } else {
            response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
            response.getWriter().write("too many request!!!");
            response.getWriter().flush();
            return;
        }
    }

}
